<script setup>
import { ref, reactive, computed,onMounted } from 'vue'
import {ElTable, ElTableColumn, ElButton, ElInput, ElSelect, ElOption, ElMessage, ElPagination} from 'element-plus'
import { getOwnerVoList } from '@/api/owner/owner' // 引入API
import {uploadFile} from "@/api/owner/owner";
import { useRouter } from 'vue-router' // 引入 useRouter
import request from "@/utils/request.js";

// 模拟数据
const tableData = ref([])

// 查询条件
const searchForm = reactive({
  keyword: '', // 统一搜索关键词
  communityName: '',
  buildingName: '',
  userName: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false) // 加载状态
const uploadDialogVisible = ref(false)
// 小区选项
const communityOptions = ref(['万象城', '万达文旅城', '碧桂园'])

// 表格的数据
const filteredData = ref([])
const fileList = ref([]) // 添加缺失的文件列表变量
const router = useRouter()



//初始数据
const initData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    // 添加搜索条件
    if (searchForm.keyword) {
      // 关键词搜索：后端应该在 OwnerVo 中处理多字段搜索逻辑
      params.keyword = searchForm.keyword
    } else {
      // 精确搜索条件
      if (searchForm.communityName) params.communityName = searchForm.communityName
      if (searchForm.buildingName) params.buildingName = searchForm.buildingName
      if (searchForm.userName) params.userName = searchForm.userName
    }
    console.log('查询参数:', params) // 调试用
    const response = await getOwnerVoList(params)
    // 转换字段名：将 owner_type 转换为 ownerType
    filteredData.value = response.rows.map(item => ({
      ...item,
      ownerType: item.owner_type  // 关键：转换字段名
    }))
    total.value = response.total
    ElMessage.success('查询成功')
    console.log('API返回原始数据:', response.rows)
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
    filteredData.value = []  // 这里应该是 filteredData 而不是 tableData
    total.value = 0
  } finally {
    loading.value = false  // 确保在 finally 中关闭 loading
  }
}
// 搜索功能
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置到第一页
  initData()
}

// 重置查询
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.communityName = ''
  searchForm.buildingName = ''
  searchForm.userName = ''
  initData()
  ElMessage.info('已重置搜索条件')
}

// 绑定业主
const bindOwner = (row) => {
  router.push({
    path: '/resident/bindOwner',
    query: {
      ownerId: row.ownerId,
      ownerName: row.userName,
      houseId: row.houseId,
      communityName: row.communityName,
      buildingName: row.buildingName,
      unitCount: row.unitCount,
      roomNo: row.roomNo,
      ownerType: row.ownerType
    }
  })
  // 这里可以添加实际的绑定逻辑
}

// 成员登记
const registerMember = (row) => {
  // 绑定业主
  router.push({
    path: '/resident/memberRegister',
    query: {
      ownerId: row.ownerId,
      ownerName: row.userName,
      houseId: row.houseId,
      communityName: row.communityName,
      buildingName: row.buildingName,
      unitCount: row.unitCount,
      roomNo: row.roomNo,
      idCard: row.idCard, // 身份证号
      phonenumber: row.phonenumber,// 手机号
      ownerType: row.ownerType
    }
  })
  // 这里可以添加实际的成员登记逻辑
}

// 导入数据
// 文件上传
const handleUpload = () => {
  uploadDialogVisible.value = true;
};

// 上传成功处理，情况数组
const handleAvatarSuccess = (response, file) => {
  ElMessage.success(response.msg || '上传成功');
  fileList.value = [];
  initData();
};

// 上传失败处理
const handleUploadError = (rawFile) => {
  ElMessage.error(`上传失败: ${error.response.data.msg}`);
}

// 上传前验证
const beforeAvatarUpload =(rawFile) => {
  // 正确的Excel文件MIME类型检查
  const allowedTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
    'application/vnd.ms-excel' // .xls
  ];

  if (!allowedTypes.includes(rawFile.type)) {
    ElMessage.error('您上传的文件必须是Excel格式（.xlsx或.xls）')
    return false
  } else if (rawFile.size / 1024 / 1024 > 500) {
    ElMessage.error('您的文件最大不能超过500MB!')
    return false
  }
  return true
}

const handleDownload = async () => {
  debugger
  try {
    const timestamp = new Date().getTime();

    // 使用 request 而不是 fetch
    const response = await request({
      url: `/owner/owner/downloadOwnerModel/ownerList.xlsx?t=${timestamp}`,
      method: 'GET',
      responseType: 'blob'  // 重要：指定响应类型为 blob
    });

    console.log('下载响应:', response);

    if (!response) {
      ElMessage.error('下载响应为空');
      return;
    }

    // 创建blob对象
    const blob = new Blob([response], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });

    console.log('文件大小:', blob.size, 'bytes');

    if (blob.size === 0) {
      ElMessage.error('下载的文件为空');
      return;
    }

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'ownerList.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    console.log(response)
    ElMessage.success(response.msg || '下载成功');

  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error(error.response.data.msg);
  }
};



// 分页变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  initData();
}

// 每页数量变化处理
const handleSizeChange = (size) => {
  pageSize.value = size
  initData();
}

onMounted(() => {
  initData()
})
</script>

<template>
  <div class="resident-management">
    <!-- 顶部查询区域 -->
    <div class="search-area">
      <div class="search-left">
        <!-- 关键词搜索 -->
        <el-input
            v-model="searchForm.keyword"
            placeholder="请输入小区、楼宇名称或业主姓名搜索"
            clearable
            style="width: 320px; margin-right: 10px;"
            @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="button-group">
        <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action="http://localhost:8080/owner/owner/upload"
            :on-success="handleAvatarSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeAvatarUpload"
            :limit="3"
        >
          <el-button type="primary" icon="el-icon-upload"
                     style="padding: 4px 8px; font-size: 14px; height: 36px;" @click="handleUpload">
            导入文件上传
          </el-button>
        </el-upload>

        <el-button type="primary" icon="el-icon-download"
                   style="padding: 4px 8px; font-size: 14px; height: 36px;"
                   @click="handleDownload">
          模板文件下载
        </el-button>
      </div>
    </div>

    <!-- 中间表格区域 -->
    <div class="table-area">
      <el-table :data="filteredData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="communityName" label="所属小区" min-width="80" align="center" />
        <el-table-column prop="buildingName" label="楼宇名称" min-width="80" align="center" />
        <el-table-column prop="unitCount" label="单元数" width="70" align="center" />
        <el-table-column prop="roomNo" label="房间号" min-width="70" align="center" />
        <el-table-column prop="userName" label="业主姓名" min-width="80" align="center" />
        <el-table-column prop="phonenumber" label="业主手机号" min-width="100" align="center" />
        <el-table-column prop="idCard" label="身份证号" min-width="160" align="center" />
        <el-table-column prop="userStatus" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag
                :type="scope.row.userStatus === '0' ? 'success' : 'danger'"
                effect="light"
            >
              {{ scope.row.userStatus === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 新增业主类型列 -->
        <el-table-column prop="ownerType" label="业主类型" width="80" align="center">
          <template #default="scope">
            <el-tag
                :type="scope.row.ownerType === '户主' ? 'success' : scope.row.ownerType === '租客' ? 'warning' : 'primary'"
                effect="light"
            >
              {{ scope.row.ownerType || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" @click="bindOwner(scope.row)">
              绑定业主
            </el-button>
            <el-button size="small" @click="registerMember(scope.row)">
              成员登记
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部区域 - 分页 -->
    <div class="bottom-area">
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[3, 5, 10, 30]"
            :small="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.resident-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .search-area {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .search-left {
      display: flex;
      align-items: center;
      flex: 1;
    }

    .button-group {
      display: flex;
      gap: 10px;
      margin-left: 20px;

      // 强制所有按钮文字居中
      :deep(*) {
        .el-button {
          display: flex !important;
          align-items: center !important;
          justify-content: center !important;
          text-align: center !important;

          span {
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            width: 100% !important;
            margin: 0 auto !important;
          }
        }
      }
    }
  }

  // 调整搜索框大小
  :deep(.search-left .el-input) {
    width: 280px !important;
  }

  .table-area {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin-bottom: 20px;
  }

  .bottom-area {
    .pagination-container {
      display: flex;
      justify-content: flex-end;
      background-color: #fff;
      padding: 15px 20px;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }

  // 移除重复的 .import-buttons 样式
}
</style>